package com.hotswap.utils;

import com.hotswap.constants.ClassIdentity;
import com.hotswap.domain.ClassInfo;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;

import static com.hotswap.constants.CommonConstants.*;

public class ClassUtils {

    public static ClassInfo parseClassInfoFromDataContext(DataContext context) {
        ClassInfo classInfo = new ClassInfo();
        Project project = context.getData(CommonDataKeys.PROJECT);
        if (project == null) {
            throw new RuntimeException("is not a project");
        }
        classInfo.setProjectBasePath(project.getBasePath());

        PsiFile psiFile = context.getData(CommonDataKeys.PSI_FILE);
        if (psiFile == null) {
            throw new RuntimeException("please choose a file");
        }

        classInfo.setClassPath(psiFile.getVirtualFile().getPath());
        if (classInfo.getClassPath().endsWith(ClassIdentity.Suffix.SOURCE)) {
            classInfo.setClassType(ClassIdentity.Type.SOURCE);
        } else {
            throw new RuntimeException("this file is neither java");
        }
        String substring = classInfo.getClassPath().substring(0, classInfo.getClassPath().length() - 5);
        String[] arr = substring.split(PATH_SEPARATOR);
        classInfo.setSimpleName(arr[arr.length - 1]);
        String[] qualifiedNameArray = substring.split(JAVA_PATH_TOKEN);
        classInfo.setQualifiedName(qualifiedNameArray[qualifiedNameArray.length - 1].replaceAll(PATH_SEPARATOR, CLASS_SEPARATOR));
        return classInfo;
    }
}
